from changer.eschanger import ElasticSearchChanger
from querier.esquerier import ElasticSearchQuerier


class JDGoodInfoQuerier(ElasticSearchQuerier):
    def __init__(self, es, index, doc_type):
        super(JDGoodInfoQuerier, self).__init__(None, None, None)
        self.es = es
        self.index = index
        self.doc_type = doc_type

    def search(self, args):
        id_ = args.get('goods_id')
        if id_ is None:
            return {"message": "goods_id is needed"}
        if id_ is not None:
            res = self.es.get(index=self.index, doc_type=self.doc_type, id=id_)
            return self._build_result(res, None)

    def _build_query(self, args): pass

    def _build_result(self, es_result, param):
        if es_result['found']:
            source_ = es_result['_source']
            return source_


class JDPriceModifyChanger(ElasticSearchChanger):
    def __init__(self, es, index, doc_type):
        super(JDPriceModifyChanger, self).__init__(es, index, doc_type)
        # change the some index
        self.jd_good_info = JDGoodInfoQuerier(es, index, doc_type)

    def _build_data(self, args):
        id_ = args.get('goods_id')
        price = args.get('price')
        if id_ is None:
            return {"message": "goods_id is needed"}
        if price is None:
            return {"message": "price is needed"}

        data = self.jd_good_info.search({'goods_id': id_})
        if not data:
            data = {}
        data['goods_id'] = id_
        data['price'] = price
        return id_, data
